ListView能將數據內容透過adapter按照順序顯示出來的列表
若數據量太多倒是無法在螢幕全部顯示時,ListView會變成可滑動式
拉一個ListView元件
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="@+id/ListView"
android:layout_width="match_parent"
android:layout_height="200dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
一開始先宣告與綁定我們ListView元件
ListView listView;
listView = findViewById(R.id.ListView);
接著創建一陣列來存放要顯示的內容
String[] str = {"水星", "金星", "地球", "火星", "木星", "土星", "天王星", "海王星"};
最後就是建立一個Adapter讓內容顯示出來
創建Adapter需要給予3個參數
1. context(ListView所在的Activity)
2. ListView列表欄的樣式,也可以自己設計(這裡我選擇系統提供的)
3. 要顯示的內容、數據
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(MainActivity.this
,android.R.layout.simple_list_item_1
,str);
這些都放入後就成功創建完一個Adapter
然後把Adapter放入ListView就大功告成
listView.setAdapter(adapter);
裡面的position表示ListView列表得位置,大小會依照內容從0開始算
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(MainActivity.this, str[position], Toast.LENGTH_SHORT);
}
});
完整程式碼
package com.example.listview_demo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView;
listView = findViewById(R.id.ListView);
String[] str = {"水星", "金星", "地球", "火星", "木星", "土星", "天王星", "海王星"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,str);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(MainActivity.this, str[i], Toast.LENGTH_SHORT).show();
}
});
}
}